﻿/*
* ========================================================================
* 类说明：
*   
* 
* 作者：HGS   时间：2024/9/4 19:55:04
* 
* 修改者：         时间：           
* 修改说明：
* ========================================================================
*/

using HslCommunication;
using HslCommunication.Profinet.Siemens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PopupWinTool.Common
{
    public class IOHelper
    {
        private ModbusTcpUnityHSL ModbusTcpClient { get; set; }
        public bool IsOpen { get; set; } = false;
        public string Message { get; private set; }

        public IOHelper()
        { }
        public bool Open(string ip,int port)
        {
            Message = string.Empty;

            if (IsOpen)
                return true;

            if (ModbusTcpClient == null)
            {
                ModbusTcpClient = new ModbusTcpUnityHSL(ip, port);
            }
            var 连接结果 = ModbusTcpClient.Connect();
            if (!连接结果)
            {
                Message = $"打开失败！！！";
                return false;
            }

            IsOpen = true;
            return true;
        }
        public bool Close()
        {
            if (!IsOpen)
            {
                return true;
            }

            var 关闭结果 = ModbusTcpClient.Close();
            if (!关闭结果)
            {
                ModbusTcpClient.Close();  //关闭失败再执行一次关闭操作，然后直接返回true
            }
            IsOpen = false;
            return true;
        }
        public bool ReadDI(int bit,out bool 读取结果, out string 错误信息)
        {
            读取结果 = false;
            错误信息 = "";

            if (!IsOpen)
            {
                Message = $"服务未连接！！！";
                return false;
            }

            int count = 3;
            bool result = false;
            for (int i = 0; i < count; i++)
            {
                var ret = ModbusTcpClient.ModbusTcpNet.ReadDiscrete(bit.ToString());
                if (ret.IsSuccess)
                {
                    result = ret.Content;
                    break;
                }
            }
            读取结果 = result;

            return true;
        }
    }
}
